package org.i1510.base.utils.encryption;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import sun.misc.BASE64Encoder;

public class BASE64Util {

	public static String File2BASE64(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
	// String imgFile = "c:/test1.gif";//待处理的图片
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
	}

	/**
	 * @author Kenshinbo@163.com
	 * @描述：Buffer编码
	 * @param str
	 * @return
	 * @version BASE64Util.java,v 1.1 Sep 3, 2013 4:32:24 PM KB
	 */
	public static String BASE64Encoder(String str) {
		if (str == null)
			return null;
		sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
		return encoder.encodeBuffer(str.getBytes()).trim();
	}

	/**
	 * @author Kenshinbo@163.com
	 * @描述：Buffer解析
	 * @param str
	 * @return
	 * @version BASE64Util.java,v 1.1 Sep 3, 2013 4:33:21 PM KB
	 */
	public static String BASE64Decoder(String str) {
		if (str == null)
			return null;
		sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
		try {
			return new String(dec.decodeBuffer(str));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";
	}

	public static void main(String[] args) {
		System.out.println(BASE64Util.BASE64Decoder("a2Vuc2hpbmJv"));
		System.out.println(BASE64Util.BASE64Encoder("men"));
		System.out.println(BASE64Util.BASE64Encoder("admin"));
	}

}
